//用户管理的 路由
//1,引入 express框架
const express = require("express");//第2次加载模块的缓存
const db = require("../modules/DBhelper");
const moment = require("moment");
//2.聘请保安大爷 (创建);

let router = express.Router();
router.get('/checkname', async (request, response, next) => {
    try {
        let sql = "SELECT*FROM userinfo WHERE u_name=? ;";
        let result = await db.exec(sql, [request.query.uname]);
        let isChekeName = !(result && result.length >= 1);
        response.end(isChekeName + '');
    } catch (error) {
        response.end('false')
    }
})

router.post("/login", async function (request, resposne, next) {
    //1.得到前端传过来的数据
    let userObj = request.body;
    let sql = " SELECT*FROM userinfo WHERE u_name=? AND u_pwd=? ;";
    let params = [
        userObj.uname,
        userObj.upwd
    ];
    let result = await db.exec(sql, params);
    let isLogin = result && result.length >= 1;
    if (isLogin) {
        delete (result[0].u_pwd);// 是u_pwd,这个字段来自于数据库
    }
    let messages = {
        msg: isLogin ? "登录成功" : "登录失败",
        data: isLogin ? result : '',
        status: isLogin ? 200 : -200
    }

    resposne.json(messages);


})
router.post("/reg", async function (request, resposne, next) {
    //1.得到前端传过来的数据
    let userObj = request.body;
    //2. sql
    let sql = " INSERT INTO `userinfo` ( `u_name`,`u_pwd`) VALUE (?,?);";
    let prams = [
        userObj.uname,
        userObj.upwd,
        // userObj.uphone,
        // moment().format("YYYY-MM-DD HH:mm:ss")
    ];

    let result = await db.exec(sql, prams);
    let isReg = result && result.affectedRows >= 1;
    let messages = {
        msg: isReg ? "注册成功" : "注册失败",
        status: isReg ? 200 : -200
    }
    resposne.json(messages);
})





//暴露
module.exports = { router };


//http//127.0.0.1:8080/account/login
//http//127.0.0.1:8080/account/reg